package com.lanyuan.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 日期工具类
 */
public class DateTimeUtil {

    private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    private static SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 获取 Calendar
     *
     * @return
     */
    public static Calendar getCalendar() {
        return Calendar.getInstance();
    }

    /**
     * 获取本地日期
     *
     * @return
     */
    public static Date getLocalDate() {
        Calendar calendar = getCalendar();
        return calendar.getTime();
    }

    /**
     * 获取本地日期时间格式字符串
     * @return
     */
    public static String getLocalStrDate() {
        Calendar calendar = getCalendar();
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(calendar.get(Calendar.YEAR));
        stringBuilder.append("-");
        stringBuilder.append(autoSupple0(calendar.get(Calendar.MONTH) + 1));
        stringBuilder.append("-");
        stringBuilder.append(autoSupple0(calendar.get(Calendar.DAY_OF_MONTH)));
        stringBuilder.append(" ");
        stringBuilder.append(autoSupple0(calendar.get(Calendar.HOUR_OF_DAY)));
        stringBuilder.append(":");
        stringBuilder.append(autoSupple0(calendar.get(Calendar.MINUTE)));
        stringBuilder.append(":");
        stringBuilder.append(autoSupple0(calendar.get(Calendar.SECOND)));
        return stringBuilder.toString();
    }

    /**
     * 获取本地日期时间格式字符串
     * @return
     */
    public static String getLocalStrDate5() {
        Calendar calendar = getCalendar();
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(calendar.get(Calendar.YEAR));
        stringBuilder.append("-");
        stringBuilder.append(autoSupple0(calendar.get(Calendar.MONTH) + 1));
        stringBuilder.append("-");
        stringBuilder.append(autoSupple0(calendar.get(Calendar.DAY_OF_MONTH)));
        stringBuilder.append(" ");
        stringBuilder.append(autoSupple0(calendar.get(Calendar.HOUR_OF_DAY)));
        stringBuilder.append(":");
        stringBuilder.append(autoSupple0(calendar.get(Calendar.MINUTE)));
        return stringBuilder.toString();
    }

    /**
     * 获取本地日期时间格式字符串
     * @param date
     * @return
     */
    public static String getLocalStrDate(Date date) {
        return dateFormat.format(date);
    }

    /**
     * 获取本地日期时间格式字符串
     * @param date
     * @return
     */
    public static String getStrDate(Date date,String format) {
        return new SimpleDateFormat(format).format(date);
    }

    /**
     * 将获取的日期的单位前如果是单个长度自动补0
     * @param
     */
    public static String autoSupple0(int unit) {
        return (unit + "").length() > 1 ? unit + "" : "0" + unit;
    }


    /**
     * 输入20180819  返回2018-08-19
     *
     * @return
     */
    public static String getFormatDateStr(String dateStr) {
        return dateStr.substring(0, 4) + "-" + dateStr.substring(4, 6) + "-" + dateStr.substring(6, 8);
    }

    /**
     * int毫秒数转String yyyy-MM-dd格式时间
     *
     * @param time
     * @return
     */
    public static String timeStampToDate(long time) {
        if (time != 0) {
            Calendar calendar = getCalendar();
            calendar.setTimeInMillis(time);
            return dateFormat.format(calendar.getTime());
        } else {
            throw new RuntimeException("时间格式不正确");
        }
    }


    /**
     * int毫秒数转String yyyy-MM-dd HH:mm:ss 格式时间
     *
     * @param time
     * @return
     */
    public static String timeStampToDateTime(long time) {
        if (time != 0) {
            Calendar calendar = getCalendar();
            calendar.setTimeInMillis(time);
            return dateTimeFormat.format(calendar.getTime());
        } else {
            throw new RuntimeException("时间格式不正确");
        }
    }


    /**
     * 获得当前时间戳  int类型
     *
     * @return
     */
    public static int getCurrentTimestamp() {
        return (int) getLocalDate().getTime() / 1000;
    }


    /**
     * 输入2019-05-10, 制定符号 如"-"
     *
     * @return 20190510
     */
    public static String replaceTimeDelimiter(String timeStr, String replaceOldStr, String replaceNewStr) {
        return timeStr.replaceAll(replaceOldStr, replaceNewStr);
    }


    /**
     * 从一段日期中,获取每个日期在整个时间段内的占比
     * ---------------------------------------------------------------------
     * -- Example：<br>
     * -- 输入 20190313 12:00:00 和 20190315 12:00:00
     * -- 输出 [20190313,0.25] [20190314,0.5] [20190315,0.25]
     * --------------------------------------------------------------------- 13
     */
    public static HashMap<String, Double> getDateAndRate(String stime, String etime) throws ParseException {
        HashMap<String, Double> map = new HashMap<String, Double>();
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
        long s0 = df.parse(stime).getTime();
        long s1 = df.parse(etime).getTime();
        long all = s1 - s0;

        ArrayList<String> list = getDateListBetween2Day(stime, etime);
        if (list.size() == 1) {
            map.put(list.get(0), 1.00D);
        } else {
            for (int i = 1; i < list.size() - 1; i++) {
                double res = 86400000.00D / all;
                map.put(list.get(i), res);
            }
            Double s0_rate = 1.00D * getSecondEnd(s0) / all;
            map.put(list.get(0), s0_rate);
            Double s1_rate = 1.00D * getSecondStart(s1) / all;
            map.put(list.get(list.size() - 1), s1_rate);
        }
        return map;
    }

    /**
     * 从一段时间段中获取所有日期
     * ---------------------------------------------------------------------
     * -- Example：
     * -- 输入 20190313 12:00:00 和 20190315 12:00:00
     * -- 输出 20190313 20190314 20190315
     * --------------------------------------------------------------------- 48
     */
    public static ArrayList<String> getDateListBetween2Day(String stime, String etime) throws ParseException {
        return getDateListBetween2Day(stime, etime, "yyyyMMdd");
    }

    public static ArrayList<String> getDateListBetween2Day(String stime, String etime, String date_pattern) throws ParseException {
        ArrayList<String> list = new ArrayList<String>();
        SimpleDateFormat df = new SimpleDateFormat(date_pattern);
        Calendar cal = Calendar.getInstance();
        Date sdate = df.parse(stime);
        Date edate = df.parse(etime);
        cal.setTime(sdate);
        while (edate.after(sdate)) {
            list.add(df.format(sdate));
            cal.add(Calendar.DAY_OF_MONTH, 1);
            sdate = cal.getTime();
        }
        list.add(df.format(edate));
        return list;
    }

    /**
     * 获取该时间戳距当天结束的时间
     * ---------------------------------------------------------------------
     * -- Example：<br>
     * -- 输入 20190313 12:00:00 的longtime值
     * -- 输出 20190313 12:00:00距20190313 24:00:00的毫秒差
     * ---------------------------------------------------------------------
     */
    public static long getSecondEnd(long longdate) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(longdate);
        cal.set(Calendar.HOUR_OF_DAY, 24);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        long max = cal.getTimeInMillis();
        return max - longdate;
    }

    /**
     * 获取该时间戳距当天开始的时间
     * ---------------------------------------------------------------------
     * -- Example：
     * -- 输入 20190313 12:00:00 的longtime值
     * -- 输出 20190313 12:00:00距20190313 00:00:00的毫秒差
     * ---------------------------------------------------------------------
     */
    public static long getSecondStart(long longdate) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(longdate);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        long min = cal.getTimeInMillis();
        return longdate - min;
    }

    /**
     * 获取当前周的第一天
     * @param date
     * @return
     */
    public static Date getFirstDayOfWeek(Date date) {
        Calendar cal = Calendar.getInstance();
        try {
            cal.setTime(date);
            cal.set(cal.DAY_OF_WEEK, cal.MONDAY);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return cal.getTime();
    }

    /**
     * 获取当前周最后一天
     * @param date
     * @return
     */
    public static Date getLastDayOfWeek(Date date) {
        Calendar cal = Calendar.getInstance();
        try {
            cal.setTime(date);
            cal.set(cal.DAY_OF_WEEK, cal.MONDAY);
            cal.set(Calendar.DATE, cal.get(Calendar.DATE) + 6);
        } catch(Exception e) {
            e.printStackTrace();
        }
        return cal.getTime();
    }

    /**
     * 获取本月开始日期
     * @return String
     * **/
    public static Date getMonthStart(){
        Calendar cal=Calendar.getInstance();
        cal.add(Calendar.MONTH, 0);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        return cal.getTime();
    }

    /**
     * 获取本月最后一天
     * @return String
     * **/
    public static Date getMonthEnd(){
        Calendar cal=Calendar.getInstance();
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
        return cal.getTime();
    }


    /**
     * 获取当年的第一天
     * @return
     */
    public static Date getCurrYearFirst(){
        Calendar currCal=Calendar.getInstance();
        int currentYear = currCal.get(Calendar.YEAR);
        return getYearFirst(currentYear);
    }

    /**
     * 获取当年的最后一天
     * @return
     */
    public static Date getCurrYearLast(){
        Calendar currCal=Calendar.getInstance();
        int currentYear = currCal.get(Calendar.YEAR);
        return getYearLast(currentYear);
    }

    /**
     * 获取某年第一天日期
     * @param year 年份
     * @return Date
     */
    public static Date getYearFirst(int year){
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        return calendar.getTime();
    }

    /**
     * 获取某年最后一天日期
     * @param year 年份
     * @return Date
     */
    public static Date getYearLast(int year){
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        calendar.roll(Calendar.DAY_OF_YEAR, -1);
        return calendar.getTime();
    }


    /**
     * 获取两个日期之间的日期
     * @param startTime
     * @param endTime
     * @return
     */
    public static List<String> getDays(String startTime, String endTime) {

        // 返回的日期集合
        List<String> days = new ArrayList<String>();
        try {
            Date start = dateFormat.parse(startTime);
            Date end = dateFormat.parse(endTime);

            Calendar tempStart = Calendar.getInstance();
            tempStart.setTime(start);

            Calendar tempEnd = Calendar.getInstance();
            tempEnd.setTime(end);
            tempEnd.add(Calendar.DATE, +1);// 日期加1(包含结束)

            while (tempStart.before(tempEnd)) {
                days.add(dateFormat.format(tempStart.getTime()));
                tempStart.add(Calendar.DAY_OF_YEAR, 1);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return days;
    }


}
